﻿using CKS.Core.Framework;
using FreeSql;
using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.Components.Web;
using Newtonsoft.Json;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.System {

    public class OEEStatisticsAction : PLCAction {

        private const string faultActionKey = "fail"; // 故障点位的ActionKey
        private const string manualActionKey = "manual"; // 手动点位的ActionKey
        private const string autoActionKey = "auto"; // 自动点位的ActionKey
        private const string standbyActionKey = "standby"; // 待料点位的ActionKey

        public OEEStatisticsAction(DecodeValue value) : base(value) {

        }

        //TODO
        public override void Execute(Dictionary<string, object> execParams) {
           
            using (var ObjectCo = base.FreeSql.Ado.MasterPool.Get()) {
                //db
                var conn = ObjectCo.Value;

                //当前点位信息
                var postionData = DecodeValue.Position;

                //当前PLCId
                var plc_id = DecodeValue.SiemensClient.PlcInfo.Id;

                //当前BlockDb
                var block_db = DecodeValue.Position.BlockDb;

                //当前点位值
                var result = DecodeValue.Value.ToBool();

                int affrows = 0;
                switch (postionData.ActionKey?.ToLower()) {
                    case faultActionKey:
                        //处理故障逻辑
                        var rec = conn.Select<CksDeviceRunRecord>()
                             .Where(o => o.PlcId == plc_id && o.DbBlock == block_db)
                             .ToOne();

                        if (result && rec == null) {

                            var cksDeviceRunRecord = new CksDeviceRunRecord() {
                                PlcId = plc_id,
                                DbBlock = block_db,
                                StartTime = DateTime.Now,
                                EndTime = null,
                                EffectType = 99,
                                CreateTime = DateTime.Now,
                            };

                            affrows = conn.Insert(cksDeviceRunRecord).ExecuteAffrows();

                        } else if (result = false && rec.EndTime == null) {

                            rec.EndTime = DateTime.Now;
                            rec.Duration = (int)(rec.EndTime.Value - rec.StartTime).TotalSeconds;
                            affrows = conn.Update<CksDeviceRunRecord>().SetSource(rec).ExecuteAffrows();

                        }
                        break;
                    default:
                        break;
                }

                //Debug.WriteLine($"OEE统计数据: {JsonConvert.SerializeObject(oeeData)}");
            }
        }
       
    }
}
